package lac.serviceuint.tool;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class StringToTypeInstantiation {

	private static ObjectMapper objectMapper = new ObjectMapper();
	private static Set<String> basicType = new HashSet<>();
	static{
		objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
		basicType.add("String");
		basicType.add("Integer");
		basicType.add("Boolean");
		basicType.add("Long");
		basicType.add("BigDecimal");
		basicType.add("Date");
		basicType.add("List");
		basicType.add("Array");
		basicType.add("Map");
	}
	
	public static Object instance(String type, String value) throws Exception {
		Object o = null;
		switch (type) {
			case "String":
				o = value;
				break;
			case "Integer":
				o = Integer.valueOf(value);
				break;
			case "Boolean":
				o = Boolean.valueOf(value);
				break;
			case "Long":
				o = Long.valueOf(value);
				break;
			case "BigDecimal":
				o = new BigDecimal(value);
				break;
			case "Date":
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
				o = sdf.parse(value);
				break;
			case "List":
				o = objectMapper.readValue(value, ArrayList.class);
				break;
			case "Array":
				o = objectMapper.readValue(value, ArrayList.class).toArray();
				break;
			case "Map":
				o = objectMapper.readValue(value, LinkedHashMap.class);
				break;
			default:
				o = objectMapper.readValue(value, Class.forName(type));
		}
		return o;
	}
	
	public static boolean isBasicType(String type){
		if(basicType.contains(type)){
			return true;
		}
		return false;
	}
	
	public static Object transformTypeObject(String type,Object obj) throws Exception{
		Class clazz =null;
		try{
			clazz = Class.forName(type);
		}catch (Exception e) {
			e.printStackTrace();
		}
		if(clazz!= null){
			return objectMapper.readValue(objectMapper.writeValueAsString(obj), clazz);
			
		}else{
			return obj;
		}
	}
}
